import { ipcRenderer, remote } from 'electron';
import  Trans from './trans/Trans.js'
import StrTo from "./lex/StrTo.js";
import Row from "./trans/basics/Row.js";
import File from "./trans/basics/File.js";
import Core from "./trans/Core.js";
import Entry from "./trans/control/Entry.js";
import AnalogyChange from "./trans/tools/AnalogyChange.js";
import Block from "./trans/basics/Block.js";
const { Menu, MenuItem, dialog } = remote;

let currentFile = null; //当前文档保存的路径
let isSaved = true;     //当前文档是否已保存
let trans=Core.instance();
trans.init();
let txtEditor = document.getElementById('txtEditor'); //获得TextArea文本框的引用
let txtEditor1 = document.getElementById('txtEditor1'); //获得TextArea文本框的引用
let txtEditor3 = document.getElementById('txtEditor3');
document.title = "Notepad - Untitled"; //设置文档标题，影响窗口标题栏名称

let txtEditor4 = document.getElementById('txtEditor4'); //获得TextArea文本框的引用
let txtEditor5 = document.getElementById('txtEditor5');

const manageWindowBtn = document.getElementById('manage-window')

manageWindowBtn.addEventListener('click',function () {
    ipcRenderer.send('oepnZi', 'exit')
})
const manageYiBtn = document.getElementById('manage-yi')

manageYiBtn.addEventListener('click',function () {
    let str=txtEditor1.value;
    let res= Sentence.run(str)
        txtEditor3.value=res;
})
const manageYiBtn1 = document.getElementById('manage-yi1')

manageYiBtn1.addEventListener('click',function () {
    let str=txtEditor4.value;
    let sentenc=new Sentence();
    let res= sentenc.run1(str)
    txtEditor5.value=res;
})

//给文本框增加右键菜单
const contextMenuTemplate=[
    { role: 'undo' },       //Undo菜单项
    { role: 'redo' },       //Redo菜单项
    { type: 'separator' },  //分隔线
    { role: 'cut' },        //Cut菜单项
    { role: 'copy' },       //Copy菜单项
    { role: 'paste' },      //Paste菜单项
    { role: 'delete' },     //Delete菜单项
    { type: 'separator' },  //分隔线
    { role: 'selectall' } ,  // //Select All菜单项
];
const contextMenu=Menu.buildFromTemplate(contextMenuTemplate);
contextMenu.append(new MenuItem({
    label: "打开代码子窗口",
    click(){
        console.log("xxxxxxxxx")
        ipcRenderer.send  ('oepnZi' ); //点击后向主页渲染进程发送“保存文件”的命令
    }
}));
contextMenu.append(new MenuItem({
    label: "发送代码到子窗口",
    click(){
        codeOutMes();
    }
}));

txtEditor.addEventListener('contextmenu', (e)=>{
    e.preventDefault();
    contextMenu.popup(remote.getCurrentWindow());
});



// 发送接收 code代码
function   codeOutMes( ) {
    const txtSave=txtEditor.value;



    let _this=this;
    let reg =new RegExp(/\n{2,}/);
    let rexList=txtSave.split(reg)
    let res="";
    let file=new File();
    for (let n=0;n<rexList.length;n++){
        let thatList=rexList[n].split("\n");
        file.addData(0,null,null,new Block())
        for (let i=0;i<thatList.length;i++){
            let wordList=thatList[i].split(',')
            file.addData(0,n,null,new Row(...wordList))
        }
    }
    let data=   file.outData();
    ipcRenderer.send('codeOutMes',{data:data,msg:"xxxxx"});
}
ipcRenderer.on('codeInMes', (event, arg) => {
    let file=new File();
    file.loadData(arg.data)
    let res="";
    for(let i=0;i<file.list.length;i++){
        let blocks=file.list[i];
        for(let l=0;l<blocks.list.length;l++){
            res+=blocks.list[l].toString()+"\n";
        }
        res+= "\n";

    }
    let reg2 =new RegExp(/\n+$/);
    res=res.replace(reg2,"")
    txtEditor.value = res;
})

//监控文本框内容是否改变
txtEditor.oninput=(e)=>{
    if(isSaved) document.title += " *";
    isSaved=false;
};

//监听与主进程的通信
ipcRenderer.on('action', (event, arg) => {
    switch(arg){        
    case 'new': //新建文件
        askSaveIfNeed();
        currentFile=null;
        txtEditor.value='';   
        document.title = "Notepad - Untitled";
        //remote.getCurrentWindow().setTitle("Notepad - Untitled *");
        isSaved=true;
        break;
    case 'open': //打开文件
        askSaveIfNeed();
        const files = remote.dialog.showOpenDialog(remote.getCurrentWindow(), {
            filters: [
                { name: "Text Files", extensions: ['txt', 'js', 'html', 'md','config','jsr'] },
                { name: 'All Files', extensions: ['*'] } ],
            properties: ['openFile']
        });
        files.then(file=>{
            currentFile=file.filePaths[0];
            const txtRead=readText(currentFile);

            document.title = "Notepad - " + currentFile;
            isSaved=true;
        })
        break;
    case 'save': //保存文件
        saveCurrentDoc();
        break;
     case 'compile': //保存文件
         compileCurrentDoc();
            break;
    case 'exiting':
        askSaveIfNeed();
        ipcRenderer.sendSync('reqaction', 'exit');
        break;
    }
});


let outType=1;

/*

ipcRenderer.on('inMes', (event, arg) => {
    switch(arg.outTyep){
        case 'A': //设置环境
               console.log(arg.mes)
            let srt3="配置依赖和启动文件，项目名称XXX，依赖都管核心包、网页基础包。"
            let wordIds= Sentence.word(srt3)
            let xx=  trans.ideaRun(wordIds);

            let file=  trans.analysisRun(xx);

            break;
    }
});
*/
//输入 接受

let entry=new Entry();
entry.run();

/**
 * 输出 函数
 */
function outMes(outType,mag,name) {
    //输出 发送
    ipcRenderer.send('outMes',{outTyep:outType,mag:mag,name:name})
}
//读取文本文件
function readText(file){
    debugger
    const fs = require('fs');
    let data=fs.readFileSync(file);
    trans.loadData(data)

}
//保存文本内容到文件
function saveText( file){
    const fs = require('fs');
    let data=  trans.outData();
    fs.writeFileSync(file, new Uint8Array(data));
}

//保存当前文档
function saveCurrentDoc(){
    if(!currentFile){

      const files = remote.dialog.showSaveDialog(remote.getCurrentWindow(), {
            filters: [
                { name: "Text Files", extensions: ['txt', 'js', 'html', 'md','config','jsr'] },
                { name: 'All Files', extensions: ['*'] } ]
        });
        files.then(file=>{
            if(file) currentFile=file.filePath;
            if(currentFile){
                const txtSave=txtEditor.value;
                saveText( currentFile);
                isSaved=true;
                document.title = "Notepad - " + currentFile;
            }
        })

    }
    if(currentFile){
        const txtSave=txtEditor.value;
        saveText( currentFile);
        isSaved=true;
        document.title = "Notepad - " + currentFile;
    }
}

//如果需要保存，弹出保存对话框询问用户是否保存当前文档
function askSaveIfNeed(){
    if(isSaved) return;
    const response=remote.dialog.showMessageBox(remote.getCurrentWindow(), {
        message: 'Do you want to save the current document?',
        type: 'question',
        buttons: [ 'Yes', 'No' ]
    });
    if(response==0) saveCurrentDoc(); //点击Yes按钮后保存当前文档
}


/**
 * 查询实体
 * 转换成文件
 * @type {HTMLElement | null}
 */
const juziBtn3 = document.getElementById('manage-yi3')
juziBtn3.addEventListener('click',function () {
    const txtSave1=txtEditor1.value;
    let real= trans.findReal(null,txtSave1,null,null)

    let rew="";
    for(let l=0;l<real.list.length;l++){
        rew+=real.list[l].toString()+"\n";
    }
    let reg1 =new RegExp(/\n+$/);
    rew=rew.replace(reg1,"")
    txtEditor3.value = rew;




})
/**
 * 实体存储
 * @type {HTMLElement | null}
 */
const juziBtn4= document.getElementById('manage-yi4')
juziBtn4.addEventListener('click',function () {
    const txtSave=txtEditor3.value;
    const realId=txtEditor1.value;
   let rows= txtSave.split("\n")
    let block=new Block();

    for(let i=0;i<rows.length;i++){
        let row= rows[i].split(',');
        block.addData(0,0,null,new Row(...row))
    }

   let readId1=  trans.upReal(block,realId)

    txtEditor1.value=readId1;
})

/**
 * 实体转换成文件
 * @type {HTMLElement | null}
 */
const juziBtn5= document.getElementById('manage-yi5')
juziBtn5.addEventListener('click',function () {
    const txtSave=txtEditor3.value;

    let rows= txtSave.split("\n")
    let block=new Block();

    for(let i=0;i<rows.length;i++){
        let row= rows[i].split(',');
        block.addData(0,0,null,new Row(...row))
    }

    let file=   AnalogyChange.toFile(block)

    let res="";
    for(let i=0;i<file.list.length;i++){
        let blocks=file.list[i];
        for(let l=0;l<blocks.list.length;l++){
            res+=blocks.list[l].toString()+"\n";
        }
        res+= "\n";

    }
    let reg2 =new RegExp(/\n+$/);
    res=res.replace(reg2,"")
    txtEditor.value = res;
})

/**
 * 文件转换成实体
 * @type {HTMLElement | null}
 */
const juziBtn6= document.getElementById('manage-yi6')
juziBtn6.addEventListener('click',function () {
    const txtSave=txtEditor.value;



    let _this=this;
    let reg =new RegExp(/\n{2,}/);
    let rexList=txtSave.split(reg)
    let res="";
    let file=new File();
    for (let n=0;n<rexList.length;n++){
        let thatList=rexList[n].split("\n");
        file.addData(0,null,null,new Block())
        for (let i=0;i<thatList.length;i++){
            let wordList=thatList[i].split(',')
            file.addData(0,n,null,new Row(...wordList))
        }
    }
    let real=   AnalogyChange.toBlock(file)

    let rew="";
    for(let l=0;l<real.list.length;l++){
        rew+=real.list[l].toString()+"\n";
    }
    let reg3 =new RegExp(/\n+$/);
    rew=rew.replace(reg3,"")
    txtEditor3.value = rew;


})


const juziBtn = document.getElementById('juzi')

juziBtn.addEventListener('click',function () {
    let srt1="配置依赖和启动文件，项目名称XXX，依赖都管核心包、网页基础包。"
    let wordIds= Sentence.word(srt1)
   let xx=  trans.word.ideaRun(wordIds);

    let file=  trans.word.analysisRun(xx);


        let res=srt1+"\n";
        res +=wordIds.toString()+"\n"
       for(let i=0;i<xx.length;i++){
           res +=   JSON.stringify(xx[i])+"\n"
       }
    txtEditor.value=res;

   let file1=  trans.word.analysisRun(xx);
   console.log(file1)
  let list=   file1.list[0].list
    console.log(file1)
    for(let i=0;i<file1.length;i++){
        res +=   file1[i].toString()+"\n"
    }
    txtEditor.value=res;
})


class Sentence{

    static  run(str){
       // outMes("A","xxx","xxx");
         let str1= str.slice(0,str.indexOf('\n'))
        let res="";
        if(str1 =='字'){
            res= this. word(str.slice(str.indexOf('\n')+1));
        }
        if(str1 =='词'){
           let swordIds= this. word(str.slice(str.indexOf('\n')+1));
            res=this.words(swordIds)
        }
        if(str1=='虚'){
            let real2=str.split('\n');
            let real3=real2[1].split(',' );

            let row= trans.findEmptyId(new Row(...real3))
            if(!row){
                row=   trans.findEmptyId(new Row(...real3),null,'1')
            }
            if(!row){
                let reodId= trans.addReal();
                let words1= new Row(...real3)
                words1.save(3,reodId)
                trans.addEmpty(words1);
                row=words1;
            }
            res=row;
        }
        if(str1 =='意'){

            let real2=str.split('\n');
            let real3=real2[1].split(',' );
            if(real2.length==3){
                let real4=real2[2].split(',' );
                if(real3.length==2){
                    trans.delIdea(0,real3[0],real3[1], new Row (...real4))
                }else {
                    let row =new Row (...real4)
                    trans.addReal(row,real3[0])
                }
            }

            let real= trans.findReal(null,real3[0],null,null)

            for(let i=0;i<real.list.length;i++){
                res+=real.list[i].toString()+"\n";
            }



        }
        return res.toString();
    }

    empthDefaultFunc(FileId,SquareId,RowId,dataThis){
        let word=this.emptyRow;
        debugger
        dataThis.list[this.id]=word

        return null;

    }
       run1(str){
        let real2=str.split('\n');
        let real3;



        if(real2.length==2){
            real3=real2[1].split(',' );
             let real1= real2[0].split(',' );

                if(real1[0]=='改'){
                    this.id=real1[1];
                   this.emptyRow= new Row(...real3)
                    let row= trans.findEmptyId(new Row(...real3),this.empthDefaultFunc.bind(this) )

                    return new Row(...real3).toString();
                }



            let row= trans.findEmptyId(new Row(...real3),null,2)
            if(!row){
                row=   trans.findEmptyId(new Row(...real3),null,'1')
            }
            if(!row){
                let words2= new Row(...real3)
                let reodId= trans.addReal(words2);
                let words1= new Row(...real3)
                words1.save(3,reodId)
                trans.addEmpty(words1);
                row=words1;
            }
            return row.toString();
        }



            real3=str.split(',' );


        let row= trans.findEmptyId(new Row(...real3))
        if(!row){
            row=   trans.findEmptyId(new Row(...real3),null,'1')
        }
        if(!row){
            let words2= new Row(...real3)
            let reodId= trans.addReal(words2);
            let words1= new Row(...real3)
            words1.save(3,reodId)
            trans.addEmpty(words1);
            row=words1;
        }
        return row.toString();
    }
    analysis(){

    }


    /**
     * 字
     * @param strNums
     */
    static word(str){
        //拆分直接添加
        let res=[];
        let srts=str.split("");
        for(let i=0;i<srts.length;i++){
            let num= StrTo.utf8ToNum(srts[i]);
            let wordId =trans.word.addWord(num);
            res.push(wordId)
        }
        return res;

    }

    /**
     * 通过字或者词添加意
     * 意
     */
    idea(){
        //判断是字还是词
        //    如果是词查找是否存在，不存在创建
        //查找意是否存在，不存在创建

    }

    /**
     * 组词
     */
    static words(wordIds){
        return  trans.word.addWrods(wordIds[0],wordIds[1])
        //查找每个字是否存在
        //组词 某认情况下不创建，除非添加意
    }



}
